<template>
  <MenuPage 
      :data="deviceList" 
      :columns="deviceCol"
      :page.sync="devicePage"
      :size.sync="devicePageSize"
      :total="totalCount"
      :loading="tableLoading"
      showSelectTag
      :selection.sync="selectIcons" 
      @queryFun="getDeviceList">
    <template slot="search">
      <div style="display: flex;justify-content: flex-end">
        <Button ghost type="primary" icon="ios-cloud-upload-outline" v-if="distributed"
          @click="reportedDevices">设备上报</Button>
        <Select filterable @on-change="searchItem" v-model="rangeId" style="width:155px;margin-left:15px"
          :placeholder="'靶场:' + mainRange" clearable v-if="distributedRange">
          <Option v-for="(items, index) in rangeAllList" :value="items.id" :key="index + 'range'">{{ items.name }}
          </Option>
        </Select>
        <i-select v-model="deviceType" placeholder="是否分配" style="margin-left:15px;width: 150px"
          @on-change="selectDeviceTypeChange" clearable>
          <i-option value="1">已分配</i-option>
          <i-option value="0">未分配</i-option>
        </i-select>
        <i-Select v-model="types" @on-change="searchDeviceNameBtn" placeholder="设备类型"
          style="margin-left:15px;width: 150px" clearable>
          <Option :value="type.value" v-for="(type,index) in typeList" :key="type.value">{{ type.label}}</Option>
        </i-Select>
        <Input v-model.trim="searchDeviceInput" clearable placeholder="设备名称" @on-change="searchDeviceNameBtn"
          style="width: 180px;margin-left: 15px" />
        <Input v-model.trim="searchDeviceIP" clearable placeholder="设备IP" @on-change="searchDeviceIPBtn"
          style="width: 180px;margin-left: 15px" />
        <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;"
          @click="refreshDevice()">
          <i class="el-icon-refresh-right" />
        </Button>
      </div>
    </template>
    <DrawerPage  width="800" v-model="addDeviceModel" title="实物设备分配"
      :on-visible-change="changeModalStatus" :columns="memCol" :data="comMemberList" :showPage="false">
      <div style="display: flex;justify-content: space-between;">
        <div style="margin-left: 15px;font-size: 14px;font-weight: bold">
          单位内设计师（{{ this.userTotal }}）
        </div>
        <Input v-model.trim="addSearchComMemInput" clearable placeholder="用户名" style="width: 200px"
          @on-change="addSearchComMem" @on-clear="clearInput" />
      </div>
      <Divider style="margin:10px 0"/>
      <!-- <div>
        <Table :columns="memCol" :data="comMemberList" :max-height="setUserTableHei"></Table>
      </div> -->
      <div slot="bottom" style="display: flex;justify-content: flex-start;margin-top: 20px">
        <Button style="margin-right: 8px" type="primary" @click="addAssign">分配</Button>
        <Button @click="addDeviceModel = false">取消</Button>
      </div>
    </DrawerPage>
</MenuPage>
</template>
<script>
  import $ from 'jquery';
  import encryption from '@/libs/encryption.js';
  import {
    getDeviceData,
    getAllDesigner,
    getSingleDeviceInfo,
    cancelDistribution,
    getAllDesignerUserName,
    DistributionForDesigner
  } from '@/api/device.js';
  import { reportedDevices, getRangeAll } from '@/api/reported-data';
  import resourcesReportedMixin from '@/mixin/resources-reported-mixin';
  import pageTitle from '@/mixin/pageTitle';
  import { debounce } from '@/libs/utils';
  export default {
    components: {},
    mixins: [resourcesReportedMixin, pageTitle],
    data() {
      return {
        mainRange: '',
        rangeAllList: [],
        selectAllIcon: false,
        selectIcons: [],
        //分布式主靶场
        // distributedRange:false,
        // 用户信息
        USER_ID: '',
        isRootDesigner: '',
        companyId: '',
        distributed: false,
        // 页面设置
        fullHeight: document.documentElement.clientHeight,
        fullWidth: document.documentElement.clientWidth,
        contentHei: 'auto',
        setTableHei: 'auto',
        // 单位所有的设计师
        allDesigner: [],
        // 设备列表
        totalCount: 0,
        devicePage: 1,
        devicePageSize: 12,
        deviceList: [],
        tableLoading:true,
        deviceCol: [
          {
              type: 'selection',
              width: 60,
              align: 'left',
              show:() => {
                return this.distributed
              }
          },
          {
            title: '名称',
            key: 'name',
            minWidth: 100,
            tooltip: true
          },
          {
            title: '是否分配',
            minWidth: 100,
            key: 'isAssign',
            filter: (isAssign) => {
              return this.isFenpei(isAssign).text;
            },
            setColor: (isAssign) => {
              return this.isFenpei(isAssign).color;
            }
          },
          {
            title: 'ID',
            key: 'id',
            minWidth: 100,
            tooltip: true
          },
          {
            title: '类型',
            key: 'type',
            minWidth: 100,
            tooltip: true,
            filter: (type) => {
              let typeInfo = this.typeList.find((item) => item.value === type);
              return typeInfo ? typeInfo.label : '未定义';
            }
          },
          {
            title: '操作系统',
            key: 'os',
            minWidth: 100,
            tooltip: true
          },
          {
            title: 'IP',
            key: 'ip',
            minWidth: 100,
            tooltip: true
          },
          {
            title: 'CPU(Core)',
            key: 'cpu',
            minWidth: 100,
            tooltip: true
          },
          {
            title: '硬盘(MB)',
            key: 'disk',
            minWidth: 100,
            tooltip: true
          },
          {
            title: '内存(GB)',
            key: 'ram',
            minWidth: 100,
            tooltip: true
          },
          {
            title: '协议',
            key: 'protocol',
            minWidth: 100,
            tooltip: true
          },
          {
            title: '端口',
            key: 'port',
            minWidth: 100,
            tooltip: true
          },
          {
            title: '使用人员',
            key: 'userName',
            minWidth: 100,
            tooltip: true
          },
          {
            title:'上报状态',
            key:'reportedStatus',
            show:() => {
              return this.distributed
            },
            filter:(reportedStatus) => {
              return ['0', '1'].includes(reportedStatus)
                ? '上报失败'
                : reportedStatus === '2'
                ? '上报成功'
                : '未上报'
            },
            setColor:(reportedStatus) => {
              return ['0', '1'].includes(reportedStatus)
                ? '#ed4014'
                : reportedStatus === '2'
                ? '#19be6b'
                : 'grey'
            },
            disabled:(data) => {
              return !['0', '1'].includes(data.reportedStatus)
            },
            tooltip:true,
            tooltipKey:'reportedMsg'
          },
          {
              title: '创建时间',
              key: 'assignTime',
              minWidth: 100,
              tooltip: true
          },
          {
            title: '操作',
            slot: 'action',
            width: 120,
            fixed:'right',
            opList: [
              {
                txt: '分配',
                on: {
                  click: (data) => {
                    this.addAssignBtn(data)
                  }
                },
                disabled: this.setIsClick,
                show: (data) => {
                  return data.isAssign ? false : true;
                }
              },
              {
                txt: '取消分配',
                tooltip: true,
                type: 'delete',
                title: '确定要取消分配吗？',
                on: {
                  click: (data) => {
                    this.delAssign(data)
                  }
                },
                disabled: this.setIsClick,
                show: (data) => {
                  return data.isAssign ? true : false;
                }
              }
            ]
          }
        ],
        delLoading: false,
        deviceType: '',
        rangeId: '',
        type: '',
        searchDeviceInput: '',
        searchDeviceIP: '',
        types: '',
        typeList: [
          {
              value: 'server',
              label: '服务器'
          },
          {
              value: 'client',
              label: '客户端'
          },
          {
              value: 'router',
              label: '路由'
          },
          {
              value: 'firewall',
              label: '防火墙'
          },
          {
              value: 'ids',
              label: 'IDS'
          },
          {
              value: 'waf',
              label: 'WAF'
          },
          {
              value: 'TOOLSDEVICE',
              label: '检测工具设备'
          },
          {
              value: 'TESTEDDEVICE',
              label: '被测设备'
          },
          {
              value: 'ATTACkDEVICE',
              label: '攻击模拟设备'
          }
      ],
        // 分配人员
        userTotal: 0,
        setUserTableHei: '700',
        addDeviceModel: false,
        submitAddMemLoading: false,
        memCol: [
          {
            title: '选择',
            minWidth: 60,
            key: 'checkBox',
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Radio', {
                  props: {
                    value: params.row.checkBox
                  },
                  on: {
                    'on-change': (e) => {
                      this.comMemberList.forEach((items) => {
                        this.$set(items, 'checkBox', false);
                      });
                      this.comMemberList[params.row._index].checkBox = true;
                      this.selectUserId = params.row.id;
                    }
                  }
                })
              ]);
            }
          },
          {
            title: '用户名',
            key: 'username',
            align: 'center'
          },
          {
            title: '昵称',
            key: 'nickname',
            align: 'center'
          },
          {
            title: '类型',
            key: 'type',
            align: 'center',
            render: (h, params) => {
              let text = '';
              if (params.row.type === 'designer' && params.row.role === 'leader') {
                text = '单位管理员';
              } else if (params.row.type === 'designer' && params.row.role === 'member') {
                text = '单位设计师';
              } else if (params.row.type === 'designer' && params.row.role === 'referee') {
                text = '裁判';
              }
              return h('div', text);
            }
          }
        ],
        comMemberList: [],
        deviceId: '',
        selectUserId: '',
        // 搜索人员
        addSearchComMemInput: ''
      };
    },
    created() {
      // 获取用户id
      let November = sessionStorage.getItem('November');
      November = JSON.parse(encryption.SelfUseDecrypt(November));
      this.USER_ID = November.userId;
      this.isRootDesigner = November.isRootDesigner;
      this.companyId = November.companyId;
      this.distributed = November.distributed;
      // this.distributedRange = this.$store.state.user.distributedRange
    },
    mounted() {
      // this.setStyle();
      // window.onresize = () => {
      //   this.setStyle();
      // };
      this.init();
      this.queryAllRange();
    },
    beforeDestroy(){
      
    },
    computed: {
      distributedRange() {
        return this.$store.state.user.distributedRange;
      }
    },
    methods: {
      // 设置高度
      setStyle() {
        window.fullHeight = document.documentElement.clientHeight;
        window.fullWidth = document.documentElement.clientWidth;
        this.fullHeight = window.fullHeight;
        this.fullWidth = window.fullWidth;
        this.contentHei = this.fullHeight - 60 + 'px'; // 80是头部高度  60是上下padding
        this.setTableHei = this.fullHeight - 227;
        this.setUserTableHei = this.fullHeight - 212;
        // this.devicePageSize = Math.floor(this.setTableHei / 96);
      },
      // 初始化
      init() {
        this.getAllDesigner().then(() => {
          this.getDeviceList();
        });
      },
      // 单位内成员
      getAllDesigner() {
        return new Promise((resolve, reject) => {
          getAllDesigner()
            .then((res) => {
              if (res.data.code == 1) {
                let items = res.data.data;
                for (let i = 0; i < items.length; i++) {
                  this.allDesigner.push(items[i].id);
                }
                resolve(this.allDesigner);
              }
            })
            .catch((err) => {
              console.log(err);
              this.$Message.error('服务器连接失败！');
            });
        });
      },
      // 获取设备列表
      getDeviceList() {
        this.tableLoading = true;
        this.deviceList = [];
        let query = {
          pageIndex: this.devicePage,
          pageSize: this.devicePageSize
        };
        let params = {
          companyId: this.companyId,
          type: this.types,
          rangeId: this.rangeId
        };
        if (this.deviceType != '') {
          params.assignFlag = this.deviceType;
        }
        if ($.trim(this.searchDeviceInput) != '') {
          params.name = $.trim(this.searchDeviceInput);
        }
        if (this.searchDeviceIP != '') {
          params.ip = this.searchDeviceIP;
        }
        getDeviceData(params, query)
          .then(async (res) => {
            this.tableLoading = false;
            if (res.data.code == 1) {
              this.deviceList = res.data.data.items;
              this.totalCount = +res.data.data.total;
              for (let i = 0; i < this.deviceList.length; i++) {
                let usid = this.deviceList[i].userId ? this.deviceList[i].userId : '';
                if (this.allDesigner.indexOf(usid) > -1) {
                  this.deviceList[i].isAssign = true;
                } else {
                  this.deviceList[i].isAssign = false;
                }
                // this.getDeviceInfo(this.deviceList[i].id,i)
              }
              await this.getReportedStatus_mixins(this.deviceList).then();
              if (this.deviceList && this.deviceList.length) {
                let questionIds = this.selectIcons.map((icon) => icon.id);
                let checkedNum = 0;
                this.deviceList.forEach((icon) => {
                  if (questionIds.includes(icon.id)) {
                    this.$set(icon, '_checked', true);
                    checkedNum++;
                  } else {
                    this.$set(icon, '_checked', false);
                  }
                });
                if (checkedNum && this.deviceList.length === checkedNum) {
                  this.selectAllIcon = true;
                } else {
                  this.selectAllIcon = false;
                }
              }
            }
          })
          .catch((err) => {
            console.log(err);
            this.tableLoading = false;
          });
      },
      deviceOnChange(val) {
        this.devicePage = val;
        this.getDeviceList();
      },
      selectDeviceTypeChange(val) {
        this.devicePage = 1;
        this.deviceType = val;
        this.getDeviceList();
      },
      searchDeviceNameBtn() {
        this.devicePage = 1;
        this.getDeviceList();
      },
      searchDeviceIPBtn() {
        this.devicePage = 1;
        this.getDeviceList();
      },
      refreshDevice() {
        this.devicePage = 1;
        this.deviceType = '';
        this.searchDeviceInput = '';
        this.searchDeviceIP = '';
        this.types = '';
        this.rangeId = ''
        this.getDeviceList();
      },
      // 查询单个设备的详情
      // getDeviceInfo(id,i){
      //     getSingleDeviceInfo(id)
      //         .then(res=>{
      //             if(res.data.code == 1){
      //                 let getData = res.data.data;
      //                 this.$set(this.deviceList[i],'purpose',getData.type)
      //                 this.$set(this.deviceList[i],'os',getData.os)
      //                 this.$set(this.deviceList[i],'ip',getData.ip)
      //                 this.$set(this.deviceList[i],'cpu',getData.cpu)
      //                 this.$set(this.deviceList[i],'disk',getData.disk)
      //                 this.$set(this.deviceList[i],'protocol',getData.protocol)
      //                 this.$set(this.deviceList[i],'port',getData.port)
      //                 this.$set(this.deviceList[i],'createTime',getData.createTime)
      //                 this.$set(this.deviceList[i],'ram',getData.ram)
      //             }
      //         })
      //         .catch(err=>{
      //             console.log(err)
      //         })
      // },
      // 取消分配
      delAssign(row) {
        let id = row.id;
        cancelDistribution(id)
          .then((res) => {
            if (res.data.code == 1) {
              this.$Message.success({
                content: '取消分配成功',
                duration: 3
              });
              this.getDeviceList();
            } else {
              this.$Message.error({
                content: res.data.message,
                duration: 3
              });
            }
          })
          .catch((err) => {
            console.log(err);
            this.$Message.error('服务器连接失败！');
          });
      },
      // 绑定设备
      addAssignBtn(row) {
        console.log(row);
        this.addDeviceModel = true;
        this.deviceId = row.id;
        this.selectUserId = '';
        this.addSearchComMemInput = '';
        this.searchDesigner();
      },
      // 查询设计师
      searchDesigner() {
        let setParams = '';
        if (this.addSearchComMemInput != '') {
          setParams = `?username=${this.addSearchComMemInput}`;
        }
        this.comMemberList = [];
        getAllDesignerUserName(setParams)
          .then((res) => {
            if (res.data.code == 1) {
              let items = res.data.data;
              this.userTotal = items.length;
              for (let i = 0; i < items.length; i++) {
                items[i].checkBox = false;
                this.comMemberList.push(items[i]);
              }
            } else {
              this.$Message.error({
                content: res.data.message,
                duration: 3
              });
            }
          })
          .catch((err) => {
            console.log(err);
            this.$Message.error('服务器连接失败！');
          });
      },
      addAssign() {
        this.submitAddMemLoading = true;
        let params = {
          id: this.deviceId,
          userId: this.selectUserId
        };
        DistributionForDesigner(params)
          .then((res) => {
            if (res.data.code == 1) {
              this.$Message.success({
                content: '分配成功',
                duration: 3
              });
              this.deviceId = '';
              this.addDeviceModel = false;
              this.getDeviceList();
            } else {
              this.$Message.error({
                content: res.data.message,
                duration: 3
              });
            }
            this.submitAddMemLoading = false;
          })
          .catch((err) => {
            console.log(err);
            this.submitAddMemLoading = false;
            this.$Message.error('服务器连接失败！');
          });
      },
      // 监控关闭modal
      changeModalStatus(val) {
        if (!val) {
          this.comMemberList.forEach((items) => {
            this.$set(items, 'checkBox', false);
          });
        }
      },
      // username搜索
      addSearchComMem() {
        this.searchDesigner();
      },
      // 清空input触发
      clearInput() {
        this.addSearchComMemInput = '';
        this.userTotal = '';
        //this.searchDesigner()
      },
      // 关闭抽屉
      closeDistribution() {
        this.addDeviceModel = false;
      },
      // 计算index
      handleProIndex(key) {
        return (this.devicePage - 1) * this.devicePageSize + key + 1;
      },
      // 是否分配
      isFenpei(val) {
        let obj = {
          text: '',
          color: 'rgb(237, 75, 77)'
        };
        if (val) {
          obj.text = '是';
          obj.color = 'green';
        } else {
          obj.text = '否';
        }
        return obj;
      },
      // 设置是否可点击
      setIsClick(item) {
        let getId = item.userId ? item.userId : '';
        let isFlag = false;
        if (getId === this.USER_ID || this.isRootDesigner) {
          isFlag = true;
        }
        if (!isFlag) {
          return true //{ 'pointer-events': 'none' };
        }
      },
      setImgSrc(item) {
        let getId = item.userId ? item.userId : '';
        let isFlag = false;
        if (getId === this.USER_ID || this.isRootDesigner) {
          isFlag = true;
        }
        if (isFlag) {
          return require('../../assets/project/assign.png');
        } else {
          return require('../../assets/project/dis-assign.png');
        }
      },
      setDelImgSrc(item) {
        let getId = item.userId ? item.userId : '';
        let isFlag = false;
        if (getId === this.USER_ID || this.isRootDesigner) {
          isFlag = true;
        }
        if (isFlag) {
          return require('../../assets/project/cancelAssign.png');
        } else {
          return require('../../assets/project/dis-cancelAssign.png');
        }
      },
      //选择导出设备
      handleCheckIcon(e) {
        console.log(e);
        this.selectAllIcon = e;
        this.deviceList.forEach((icon) => {
          this.checkSingleQuestion(e, icon);
        });
      },
      checkSingleQuestion(e, icon) {
        if (e && !this.selectIcons.map((icon) => icon.id).includes(icon.id)) {
          this.selectIcons.push(icon);
        } else if (!e && this.selectIcons.map((icon) => icon.id).includes(icon.id)) {
          let index = this.selectIcons.findIndex((item) => icon.id == item.id);
          this.selectIcons.splice(index, 1);
        }
        let checkudQuestion = this.deviceList.find((item) => item.id == icon.id);
        if (checkudQuestion) {
          this.$set(checkudQuestion, '_checked', e);
        }
        if (this.deviceList.length > 0 && this.deviceList.every((icon) => icon._checked === true)) {
          this.selectAllIcon = true;
        } else {
          this.selectAllIcon = false;
        }
      },
      // 上报设备
      reportedDevices() {
        if (this.selectIcons.length == 0) {
          this.$Message.warning('请选择设备');
          return;
        }
        let iconIdS = [];
        this.selectIcons.forEach((question) => {
          iconIdS.push(question.id);
        });
        reportedDevices(iconIdS)
          .then(({ code, message }) => {
            if (code !== 1) {
              this.$Message.warning(message);
              return;
            }
            this.$Message.info('上报设备成功');
            this.getDeviceList();
            this.selectIcons = [];
            this.selectAllIcon = false;
            this.deviceList.forEach((item) => this.$set(item, '_checked', false));
          })
          .catch(() => {
            this.$Message.error('上报主设备异常');
          });
      },
      //查询所有分靶场信息
      queryAllRange() {
        getRangeAll().then((res) => {
          if (res.code === 1) {
            let mainRange = res.data.items.find((item) => {
              return item.level== 'LOCAL';
            });
            this.mainRange = mainRange.name || '选择靶场';
            this.rangeAllList = res.data.items;
          }
        });
      },
      searchItem() {
        this.getDeviceList();
      }
    }
  };
</script>
<style scoped>
</style>